package com.jxpay.yspay;

import cn.hutool.core.util.StrUtil;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * <p>JXPay-银盛支付</p>
 *
 * @author JX
 */
public class YsPayApiConfigKit {

    private static final ThreadLocal<String> TL = new ThreadLocal<String>();

    private static final Map<String, YsPayApiConfig> CFG_MAP = new ConcurrentHashMap<String, YsPayApiConfig>();
    private static final String DEFAULT_CFG_KEY = "_default_key_";

    /**
     * 添加微信支付配置，每个appId只需添加一次，相同appId将被覆盖
     *
     * @param ysPayApiConfig 微信支付配置
     * @return {WxPayApiConfig} 微信支付配置
     */
    public static YsPayApiConfig putApiConfig(YsPayApiConfig ysPayApiConfig) {
        if (CFG_MAP.size() == 0) {
            CFG_MAP.put(DEFAULT_CFG_KEY, ysPayApiConfig);
        }
        return CFG_MAP.put(ysPayApiConfig.getAppId(), ysPayApiConfig);
    }

    public static YsPayApiConfig setThreadLocalWxPayApiConfig(YsPayApiConfig ysPayApiConfig) {
        if (StrUtil.isNotEmpty(ysPayApiConfig.getAppId())) {
            setThreadLocalAppId(ysPayApiConfig.getAppId());
        }
        return putApiConfig(ysPayApiConfig);
    }

    public static YsPayApiConfig removeApiConfig(YsPayApiConfig ysPayApiConfig) {
        return removeApiConfig(ysPayApiConfig.getAppId());
    }

    public static YsPayApiConfig removeApiConfig(String appId) {
        return CFG_MAP.remove(appId);
    }

    public static void setThreadLocalAppId(String appId) {
        if (StrUtil.isEmpty(appId)) {
            appId = CFG_MAP.get(DEFAULT_CFG_KEY).getAppId();
        }
        TL.set(appId);
    }

    public static void removeThreadLocalAppId() {
        TL.remove();
    }

    public static String getAppId() {
        String appId = TL.get();
        if (StrUtil.isEmpty(appId)) {
            appId = CFG_MAP.get(DEFAULT_CFG_KEY).getAppId();
        }
        return appId;
    }

    public static YsPayApiConfig getYsPayApiConfig() {
        String appId = getAppId();
        return getApiConfig(appId);
    }

    public static YsPayApiConfig getApiConfig(String appId) {
        YsPayApiConfig cfg = CFG_MAP.get(appId);
        if (cfg == null) {
            throw new IllegalStateException("需事先调用 YxPayApiConfigKit.putApiConfig(ysPayApiConfig) 将 appId 对应的 YsPayApiConfig 对象存入，才可以使用 YsPayApiConfigKit.getYsPayApiConfig() 的系列方法");
        }
        return cfg;
    }
}